using Lzfy_His_Service.Models;
using Lzfy_His_Service.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Lzfy_His_Service.Controllers
{
    /// <summary>
    /// 患者卡信息查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PatientCardInfoController : ControllerBase
    {
        private readonly IPatientCardInfoService _patientCardInfoService;
        private readonly ILogger<PatientCardInfoController> _logger;

        public PatientCardInfoController(
            IPatientCardInfoService patientCardInfoService,
            ILogger<PatientCardInfoController> logger)
        {
            _patientCardInfoService = patientCardInfoService;
            _logger = logger;
        }

        /// <summary>
        /// 查询患者卡信息
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>患者卡信息列表</returns>
        [HttpPost("query")]
        public async Task<IActionResult> QueryPatientCardInfo([FromBody] PatientCardQueryRequest request)
        {
            try
            {
                // 参数验证 - 至少需要提供一个查询条件
                if (request == null || 
                    (string.IsNullOrWhiteSpace(request.Name) && 
                     string.IsNullOrWhiteSpace(request.Phone) && 
                     string.IsNullOrWhiteSpace(request.IdNumber)))
                {
                    return BadRequest(new
                    {
                        success = false,
                        message = "至少需要提供一个查询条件（姓名、手机号或证件号）",
                        data = default(object?)
                    });
                }

                // 查询患者卡信息
                var patientCardInfoList = await _patientCardInfoService.GetPatientCardInfoAsync(request);

                _logger.LogInformation("患者卡信息查询成功，姓名: {Name}, 手机号: {Phone}, 证件号: {IdNumber}，记录数: {Count}", 
                    request.Name, request.Phone, request.IdNumber, patientCardInfoList.Count);

                return Ok(new
                {
                    success = true,
                    message = patientCardInfoList.Count > 0 ? "查询成功" : "未找到符合条件的患者卡信息",
                    data = patientCardInfoList
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "患者卡信息查询失败，姓名: {Name}, 手机号: {Phone}, 证件号: {IdNumber}", 
                    request?.Name, request?.Phone, request?.IdNumber);

                return StatusCode(500, new
                {
                    success = false,
                    message = "查询失败，请稍后重试",
                    data = default(object?)
                });
            }
        }
    }
}